from datetime import datetime
from typing import Optional, List, Dict, Any
from apps.models.models import User
from apps.schemas.schemas import UserCreateModel, UserUpdateModel
from tortoise.exceptions import DoesNotExist


async def get_all_users() -> List[Dict[str, Any]]:
    """
    获取所有用户列表
    :return: 用户列表
    """
    users = await User.all().values(
        "user_id",
        "username",
        "phone",
        "role",
    )
    return list(users)


async def get_user_by_id(user_id: int) -> Optional[Dict[str, Any]]:
    """
    根据用户ID获取用户信息
    :param user_id: 用户ID
    :return: 用户信息
    """
    user = await User.filter(user_id=user_id).values(
        "user_id",
        "username",
        "phone",
        "role",
    )
    return user[0] if user else None


async def get_user_details_by_id(user_id: int) -> Optional[Dict[str, Any]]:
    """
    根据用户ID获取用户详细信息（包含敏感信息）
    :param user_id: 用户ID
    :return: 用户详细信息
    """
    user = await User.filter(user_id=user_id).values(
        "user_id",
        "username",
        "password",
        "phone",
        "email",
        "role",
        "create_at",
        "update_at",
        "is_active",
    )
    return user[0] if user else None


async def create_user(data: UserCreateModel) -> Dict[str, Any]:
    """
    创建新用户
    :param data: 用户创建请求数据
    :return: 创建的用户信息
    """
    user = await User.create(
        username=data.username,
        password=data.password,
        email=data.email,
        phone=data.phone,
        role=data.role
    )
    return {
        "user_id": user.user_id,
        "username": user.username,
        "phone": user.phone,
        "role": user.role
    }


async def update_user(user_id: int, data: UserUpdateModel) -> bool:
    """
    更新用户信息
    :param user_id: 用户ID
    :param data: 用户更新请求数据
    :return: 更新是否成功
    """
    update_data = data.dict(exclude_unset=True)  # 只更新传入的字段
    if not update_data:
        raise ValueError("No fields to update")

    # 添加更新时间
    update_data["update_at"] = datetime.now()

    updated_count = await User.filter(user_id=user_id).update(**update_data)
    return updated_count > 0


async def delete_user(user_id: int) -> bool:
    """
    删除用户
    :param user_id: 用户ID
    :return: 删除是否成功
    """
    deleted_count = await User.filter(user_id=user_id).delete()
    return deleted_count > 0
